using System.Linq;
using Shop.Backend.Api.Entity;
using Shop.Backend.Api.Params;
using Shop.Backend.Api.Repository;
using Shop.Backend.Api.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace Shop.Backend.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class UsersController : ControllerBase
    {
        private IConfiguration _configuration;
        private IRepository<Users> _usersRepository;

        private TokenParameter _tokenParameter;


        public UsersController(IConfiguration configuration
        , IRepository<Users> usersRepository
        )
        {
            _configuration = configuration;
            _usersRepository = usersRepository;
            _tokenParameter =
                _configuration
                    .GetSection("TokenParameter")
                    .Get<TokenParameter>();
        }


        [HttpGet]
        public dynamic Get([FromQuery] QueryWithPager query)
        {
            // get请求默认从url中获取参数，如果需要使用实体接收参数，需要FromQuery特性
            var pageIndex = query.Pager.PageIndex;
            var pageSize = query.Pager.PageSize;

            var keyword = string.IsNullOrEmpty(query.Keyword) ? "" : query.Keyword.Trim();


            var users = _usersRepository.Table.Where(x => x.IsDeleted == false); ;

            // 如果keyword不为空，则再去查询用户名
            if (!string.IsNullOrEmpty(keyword))
            {
                users = users.Where(x => x.Id.ToString() == keyword
              || x.Username.Contains(keyword)
              || x.Remarks.Contains(keyword));
            }

            var u = users.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return JsonHelper.Serialize(new
            {
                Code = 1000,
                Data = new { Data = u, Pager = new { pageIndex, pageSize, rowsTotal = users.Count() } },
                Msg = "获取用户列表成功^_^"
            });
        }

        [HttpGet("{id}")]
        public dynamic Get(int id)
        {
            var user = _usersRepository.GetById(id);
            return new
            {
                Code = 1000,
                Data = user,
                Msg = "获取指定用户成功^_^"
            };
        }

        [HttpPost]
        public dynamic Post(CreateUser newUser)
        {
            var username = newUser.Username.Trim();
            var password = newUser.Password.Trim();

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "用户名或密码不能为空"
                };
            }

            //查询表中时候存在相同用户
            var userTable = _usersRepository.Table.Where(x => x.Username == username).Count();

            //如果说表没有查到数据 就视为新增用户
            if (userTable < 1)
            {

                var user = new Users
                {
                    Username = newUser.Username,
                    Password = newUser.Password,
                    UserPicture = "http://localhost:8080/6.jpg",
                    UserRole = 0,
                };

                _usersRepository.Insert(user);
                return new
                {
                    Code = 1000,
                    Data = user,
                    Msg = "创建用户成功^_^"
                };
            }
            return new
            {
                Code = 104,
                Data = "",
                Msg = "该用户已存在，请尝试其它名字 @_@!"
            };

        }
        [HttpPost, Route("password")]
        public dynamic PostPassword(CreateUser newUser)
        {
            //用户Id
            var id = newUser.id;
            //旧密码
            var username = newUser.Username.Trim();
            //新密码
            var password = newUser.Password.Trim();
            //确认密码
            var avatar = newUser.avatar.Trim();

            var user = _usersRepository.GetById(id);

            if (user == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "用户不存在"
                };
            }
            if (user.Password != username)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "密码不正确"
                };
            }

            if (string.IsNullOrEmpty(avatar) || string.IsNullOrEmpty(password))
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "两次密码不能为空"
                };
            }
            if (password != avatar)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "两次密码应该相同"
                };
            }
            user.Password = avatar;

            _usersRepository.Update(user);

            return new
            {
                Code = 200,
                Data = "",
                Msg = "修改密码成功!"
            };

        }

        [HttpPut("{id}")]
        public dynamic Put(int id, CreateUser updateUser)
        {
            var username = updateUser.Username.Trim();
            var password = updateUser.Password.Trim();

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "用户名或密码不能为空=_="
                };

            }


            var user = _usersRepository.GetById(id);

            if (user == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "要更新的用户不存在，请确认后重试=_="
                };
            }

            user.Username = updateUser.Username;
            user.Password = updateUser.Password;

            _usersRepository.Update(user);

            return new
            {
                Code = 1000,
                Data = user,
                Msg = "更新成功"
            };
        }
        //修改用户状态的方法
        [HttpPut, Route("status")]
        public dynamic PutStatus(CreateUser updateUser)
        {
            var id = updateUser.id;
            var user = _usersRepository.GetById(id);


            if (user == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "要更新的用户不存在，请确认后重试=_="
                };
            }

            user.IsActived = updateUser.IsActived;
            _usersRepository.Update(user);

            return new
            {
                Code = 1000,
                Data = user,
                Msg = "更新成功"
            };
        }



        //修改用户头像
        [HttpPost, Route("UserPicture")]
        public dynamic PutPicture(CreateUser updateUser)
        {
            // var username = updateUser.Username.Trim();
            // var password = updateUser.Password.Trim();
            var id = updateUser.id;
            var UserPicture = updateUser.avatar;

            if (string.IsNullOrEmpty(UserPicture))
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "头像不能为空"
                };

            }


            var user = _usersRepository.GetById(id);

            if (user == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "要更新的用户不存在，请确认后重试=_="
                };
            }

            user.UserPicture = "http://localhost:5000/" + updateUser.avatar;

            _usersRepository.Update(user);

            return new
            {
                Code = 1000,
                Data = user,
                Msg = "更新成功"
            };
        }

        [HttpDelete("{id}")]
        public dynamic Delete(int id)
        {
            var user = _usersRepository.GetById(id);

            if (user == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "要删除的用户不存在，请确认后重试=_="
                };
            }

            user.IsDeleted = true;
            user.IsActived = false;

            _usersRepository.Update(user);

            return new
            {
                Code = 1000,
                Data = "",
                Msg = "删除用户成功^_^"
            };
        }
        [AllowAnonymous]
        [HttpPost, Route("token")]
        public dynamic GetToken(CreateUser newUser)
        {
            var username = newUser.Username.Trim();
            var password = newUser.Password.Trim();

            var user =
                _usersRepository
                    .Table
                    .Where(x =>
                        x.Username == username && x.Password == password && x.IsDeleted == false)
                    .FirstOrDefault();


            if (user == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "用户名或密码不正确，请确认后重试"
                };
            }

            var token =
           TokenHelper.GenerateToekn(_tokenParameter, user.Username);
            var refreshToken = "112358";
            if (user.UserRole == 0)
            {
                return new
                {
                    Code = 1000,
                    Data = new
                    {
                        Token = token,
                        refreshToken = refreshToken,
                        username = user.Username,
                        userid = user.Id,
                    },
                    Msg = "用户登录成功^_^"
                };
            }
            else if (user.UserRole == 1)
            {
                return new
                {
                    Code = 10086,
                    Data = new
                    {
                        Token = token,
                        refreshToken = refreshToken,
                        username = user.Username,
                        userid = user.Id,
                    },
                    Msg = "超级管理员登录成功^_^"
                };
            }
            else if (user.UserRole == 2)
            {
                return new
                {
                    Code = 10002,
                    Data = new
                    {
                        Token = token,
                        refreshToken = refreshToken,
                        username = user.Username,
                        userid = user.Id,
                    },
                    Msg = "供应商登录成功^_^"
                };
            }
            else if (user.UserRole == 3)
            {
                return new
                {
                    Code = 10003,
                    Data = new
                    {
                        Token = token,
                        refreshToken = refreshToken,
                        username = user.Username,
                        userid = user.Id,
                    },
                    Msg = "商家登录成功^_^"
                };
            }

            return new
            {
                Code = 104,
                Data = "",
                Msg = "未知错误"
            };

        }

        [AllowAnonymous]
        [HttpPost, Route("refreshtoken")]
        public dynamic RefreshToken(RefreshTokenDTO refresh)
        {
            var username = TokenHelper.ValidateToken(_tokenParameter, refresh);

            if (string.IsNullOrEmpty(username))
            {
                return new { Code = 1002, Data = "", Msg = "token验证失败" };
            }

            var token = TokenHelper.GenerateToekn(_tokenParameter, username);
            var refreshToken = "112358";

            return new
            {
                Code = 1000,
                Data = new { Token = token, refreshToken = refreshToken },
                Msg = "刷新token成功^_^"
            };
        }


    }
}